﻿using System;
using System.Globalization;
using System.Windows.Forms;
using Common.Logging;
using InfoboardAdapterC.Common;
using NKnife.IoC;

namespace InfoboardAdapterC.Parameter
{
    public partial class ParameterConfigView : Form
    {
        private static readonly ILog _loggerLog = LogManager.GetLogger<ParameterConfigView>();
        private readonly ParameterConfigViewModel _ParameterConfigView = DI.Get<ParameterConfigViewModel>();
        private readonly ParamentConfig _ParamentConfig = DI.Get<ParamentConfig>();

        public ParameterConfigView()
        {
            InitializeComponent();
            BindingConfig();
        }

        private void BindingConfig()
        {
            _ParameterConfigView.LoadConfig(out string serviceIp,out string servicePort);
            if (serviceIp.Length == 0)
                serviceIp = "127.0.0.1";
            if (servicePort.Length == 0)
                servicePort = "7000";
            ServerIpAddress.Text = serviceIp;
            ServerPortTextBox.Text = servicePort;
            _ParamentConfig.LoadConfigTimer(out string timeTick);
            if (!int.TryParse(timeTick, out int timerV))
                timerV = 5;
            TimerNumericUpDown.Value = timerV;
            StartUpCheckBox.Checked = _ParameterConfigView.IsRegistryExist;
        }

        private void SaveButton_Click(object sender, EventArgs e)
        {

            var reslut = "保存失败,原因:";
            try
            {
                _ParameterConfigView.SaveConfig(ServerIpAddress.Text, ServerPortTextBox.Text);
                var timeTick = TimerNumericUpDown.Text;
                _ParamentConfig.SaveConfigTimer(timeTick);
                SaveRegit();
                reslut = "保存完成";
            }
            catch (Exception exception)
            {
                reslut += exception.Message;
                _loggerLog.Error(exception.Message);
            }
            MessageBox.Show(reslut);
            if (reslut == "保存完成")
            {
                Close();
            }
        }

        private void CancelButton_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void SaveRegit()
        {
            if(StartUpCheckBox.Checked)
                _ParameterConfigView.SetStarUpConfig();
            else
            {
                _ParameterConfigView.RemoveStarUpConfig();
            }
        }
    }
}
